//
//  LoginAndRegistViewController.m
//  Consume100
//
//  Created by eliot on 16/3/21.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "LoginAndRegistViewController.h"
#import "GetIdentifyingViewController.h"
#import "RegistGetIdentifyingViewController.h"
#import "MBProgressHUD+MJ.h"
#import "MBProgressHUD.h"
#import "TabBarViewController.h"
#import "UserModel.h"

#import "SecurityUtil.h"
#import "GTMBase64.h"


#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@interface LoginAndRegistViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UserModel *myUserModel;

@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;

@property (weak, nonatomic) IBOutlet UITextField *passWordTextField;

@property (weak, nonatomic) IBOutlet UIImageView *LogoIV;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoTopHeight;

@property (weak, nonatomic) IBOutlet UILabel *lb1;

@property (weak, nonatomic) IBOutlet UILabel *lb2;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logow;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoh;



@end

@implementation LoginAndRegistViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    float width = [UIScreen mainScreen].bounds.size.width;
    if (Height <= 568) {
        self.logoTopHeight.constant = 100/568.0 * Height - 34.0;
    }else {
        self.logoTopHeight.constant = 100/568.0 * Height;
    }
    self.logow.constant = 100/320.0 * width;
    self.logoh.constant= 100/320.0 * width;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *imageP = [UIImage imageNamed:@"icon_phone"];
    UIImageView *leftVP = [[UIImageView alloc]initWithImage:imageP];
    leftVP.contentMode = UIViewContentModeCenter;
    leftVP.frame = CGRectMake(0, 0, 55, 20);
    self.phoneNumberTextField.leftViewMode = UITextFieldViewModeAlways;
    self.phoneNumberTextField.leftView = leftVP;
    self.passWordTextField.delegate = self;
    self.phoneNumberTextField.delegate = self;
    UIImage *imageQ = [UIImage imageNamed:@"icon_parsword"];
    UIImageView *leftVQ = [[UIImageView alloc]initWithImage:imageQ];
    leftVQ.contentMode = UIViewContentModeCenter;
    leftVQ.frame = CGRectMake(0, 0, 55, 20);
    self.passWordTextField.leftViewMode = UITextFieldViewModeAlways;
    self.passWordTextField.leftView = leftVQ;
    self.loginBtn.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    self.loginBtn.layer.cornerRadius = 5;
    self.loginBtn.layer.masksToBounds = YES;
    self.view.backgroundColor = [UIColor whiteColor];
  //  self.phoneNumberTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.passWordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    //监听键盘通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(KeyBoardShow:)name:@"UIKeyboardWillShowNotification" object:nil];//弹出通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(KeyBoardHiden:)name:@"UIKeyboardWillHideNotification" object:nil];//隐藏 时通知
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    if (self.phoneNumberTextField.text.length > 10) {
        self.phoneNumberTextField.text = [self.phoneNumberTextField.text substringToIndex:10];
    }
    
    return canChange;
}




-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.passWordTextField resignFirstResponder];
    [self.phoneNumberTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/** 正则表达式判断手机号*/
+(BOOL)checkTelNumber:(NSString*)telNumber{
    NSString *pattern = @"^1+[3578]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}

//点击登陆按钮
- (IBAction)clickLoginBtn:(id)sender {
    
    if (![LoginAndRegistViewController checkTelNumber:self.phoneNumberTextField.text] == 0) {
        [MBProgressHUD showError:@"请输入正确的手机号码"];
    }else {
        [MBProgressHUD showMessage:@"正在登陆"];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 10;
        self.myUserModel = [[UserModel alloc] init];
        
        //加密
        NSString *name=[SecurityUtil encryptAESData:@"13888888888"];
        NSString *pwd=[SecurityUtil encryptAESData:@"123"];
        
        NSDictionary *dic = @{@"name":name,@"pwd":pwd};
   
        NSString *baseUrl = [NSString stringWithFormat:@"%@index.jhtml", MyBaseURL];
        [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *errorCode = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
            
            
            
            NSString *de = [SecurityUtil decryptAESData:errorCode];
            NSData *da = [de dataUsingEncoding:NSUTF8StringEncoding];
            
            NSArray *ar = [NSJSONSerialization JSONObjectWithData:da options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dddic = ar[0];
            
            if ([errorCode isEqualToString:@"consumerNull"]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showError:@"账号不存在"];
                });
            }else {
                if ([errorCode isEqualToString:@"errorNamePwd"]) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [MBProgressHUD hideHUD];
                        [MBProgressHUD showError:@"密码错误"];
                    });
                }else {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [MBProgressHUD hideHUD];
                        TabBarViewController *home=[TabBarViewController creatTabBarViewController];
                        UIWindow *window=[[UIApplication sharedApplication]keyWindow];
                        window.rootViewController =home;
                        [window makeKeyAndVisible];
                        
                    });
                    
                    NSLog(@"在登陆 ：%@", dddic);
                    
                    [self.myUserModel setValuesForKeysWithDictionary:dddic];
                    //归档
                    NSData *themeAndAboutData = [NSKeyedArchiver archivedDataWithRootObject:self.myUserModel];
                    [[NSUserDefaults standardUserDefaults] setObject:themeAndAboutData forKey:@"userModel"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
                //解档
//                NSData *getthemeAndAboutData = [[NSUserDefaults standardUserDefaults] objectForKey:@"userModel"];
//                UserModel *getThemeAndAbout =   [NSKeyedUnarchiver unarchiveObjectWithData:getthemeAndAboutData];
                
            
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                NSLog(@"%@", error);
                
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"链接超时,请检查网络"];
            });
        }];
    }
}

//点击注册按钮
- (IBAction)clickRegistBtn:(id)sender {
    RegistGetIdentifyingViewController *vc = [RegistGetIdentifyingViewController CreatRegistGetIdentifyingViewController];
    [self creatNav:vc];
    
}
////点击忘记密码按钮
- (IBAction)clickForgetPassWordBtn:(id)sender {
    GetIdentifyingViewController *vc = [GetIdentifyingViewController CreatGetIdentifyingViewController];
    vc.viewTitle = @"找回密码";
    [self creatNav:vc];
    
    
}


/**
 *  MAKR：监听键盘弹出
 */
-(void)KeyBoardShow:(NSNotification *)info{
    NSDictionary *dic=[info userInfo];//获取信息
    //获得键盘弹出的位移来移动view
    NSValue *value=dic[@"UIKeyboardFrameBeginUserInfoKey"];
    CGSize keyBoardSize=[value CGRectValue].size;//获得键盘size
    CGFloat keyBoardHeight=keyBoardSize.height;//键盘弹出高度是258
    CGFloat height = self.passWordTextField.frame.origin.y - (self.view.frame.size.height - keyBoardHeight - 40);
    if (height > 0) {//如果输入框再键盘下面
        height = height + 5;
        [UIView animateWithDuration:0.20 animations:^{
            self.passWordTextField.transform=CGAffineTransformMakeTranslation(0,-height);
            self.phoneNumberTextField.transform=CGAffineTransformMakeTranslation(0,-height);

            self.LogoIV.transform=CGAffineTransformMakeTranslation(0, -height);
            self.lb1.transform=CGAffineTransformMakeTranslation(0, -height);
            self.lb2.transform=CGAffineTransformMakeTranslation(0, -height);
            self.loginBtn.transform=CGAffineTransformMakeTranslation(0, -height);
        }];
    }
    
    
  
}
/**
 *  MARK:监听键盘隐藏
 *
 *  @param info
 */
-(void)KeyBoardHiden:(NSNotification *)info{
        NSDictionary *dic=[info userInfo];//获取信息
    /*
     UIKeyboardAnimationCurveUserInfoKey = 7;
     UIKeyboardAnimationDurationUserInfoKey = "0.25";  动画时间
     UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}"; bounds
     UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";起始时候的中点
     UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";弹出后的中点
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";键盘弹出前的fram
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}"; 弹出后fram
     UIKeyboardIsLocalUserInfoKey = 1; 本地键盘的key
     */
    //获得键盘弹出的位移来移动view
    //    NSValue *value=dic[@"UIKeyboardFrameBeginUserInfoKey"];
    //    CGSize keyBoardSize=[value CGRectValue].size;//获得键盘size
    //    CGFloat keyBoardHeight=keyBoardSize.height;键盘弹出高度是258
    
    //view的位移是258
    //    [UIView animateWithDuration:0.2 animations:^{
    //        self.view.transform=CGAffineTransformIdentity;
    //        self.logo.transform=CGAffineTransformIdentity;
    //    }];
    
    
    NSValue *value=dic[@"UIKeyboardFrameBeginUserInfoKey"];
    CGSize keyBoardSize=[value CGRectValue].size;//获得键盘size
    CGFloat keyBoardHeight=keyBoardSize.height;//键盘弹出高度是258
    CGFloat height = self.passWordTextField.frame.origin.y - (self.view.frame.size.height - keyBoardHeight - 40);
    if (height > 0) {//如果输入框再键盘下面
        height = height + 5;
        [UIView animateWithDuration:0.20 animations:^{
            self.passWordTextField.transform=CGAffineTransformMakeTranslation(0, height);
            self.phoneNumberTextField.transform=CGAffineTransformMakeTranslation(0, height);
            self.LogoIV.transform=CGAffineTransformMakeTranslation(0, height);
            self.lb1.transform=CGAffineTransformMakeTranslation(0, height);
            self.lb2.transform=CGAffineTransformMakeTranslation(0, height);
            self.loginBtn.transform=CGAffineTransformMakeTranslation(0, height);
        }];
    }
}


//创建模态导航控制器
-(void)creatNav:(UIViewController *)view{
    
    UINavigationController *nav=[[UINavigationController alloc] initWithRootViewController:view];
    nav.navigationBar.barTintColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    view.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
